"""
更新2025年LCK、LPL和LEC战队信息
"""
import os
import requests
import shutil
from app import create_app
from app.models.models import db, Team
import uuid

# 2025年最新战队数据
TEAMS_DATA_2025 = [
    {"name": "T1", "league": "LCK", "game": "英雄联盟"},
    {"name": "Hanwha Life Esports", "league": "LCK", "game": "英雄联盟"},
    {"name": "OKSavingsBank BRION", "league": "LCK", "game": "英雄联盟"},
    {"name": "DN Freecs", "league": "LCK", "game": "英雄联盟"},
    {"name": "BNK FEARX", "league": "LCK", "game": "英雄联盟"},
    {"name": "Dplus KIA", "league": "LCK", "game": "英雄联盟"},
    {"name": "Gen.G", "league": "LCK", "game": "英雄联盟"},
    {"name": "KT Rolster", "league": "LCK", "game": "英雄联盟"},
    {"name": "DRX", "league": "LCK", "game": "英雄联盟"},
    {"name": "Nongshim RedForce", "league": "LCK", "game": "英雄联盟"},
    
    {"name": "Anyone's Legend", "league": "LPL", "game": "英雄联盟"},
    {"name": "Bilibili Gaming", "league": "LPL", "game": "英雄联盟"},
    {"name": "EDward Gaming", "league": "LPL", "game": "英雄联盟"},
    {"name": "FunPlus Phoenix", "league": "LPL", "game": "英雄联盟"},
    {"name": "Invictus Gaming", "league": "LPL", "game": "英雄联盟"},
    {"name": "JD Gaming", "league": "LPL", "game": "英雄联盟"},
    {"name": "LGD Gaming", "league": "LPL", "game": "英雄联盟"},
    {"name": "LNG Esports", "league": "LPL", "game": "英雄联盟"},
    {"name": "Ninjas in Pyjamas", "league": "LPL", "game": "英雄联盟"},
    {"name": "Oh My God", "league": "LPL", "game": "英雄联盟"},
    {"name": "Royal Never Give Up", "league": "LPL", "game": "英雄联盟"},
    {"name": "Team WE", "league": "LPL", "game": "英雄联盟"},
    {"name": "ThunderTalk Gaming", "league": "LPL", "game": "英雄联盟"},
    {"name": "Top Esports", "league": "LPL", "game": "英雄联盟"},
    {"name": "Ultra Prime", "league": "LPL", "game": "英雄联盟"},
    {"name": "Weibo Gaming", "league": "LPL", "game": "英雄联盟"},
    
    {"name": "Fnatic", "league": "LEC", "game": "英雄联盟"},
    {"name": "Karmine Corp", "league": "LEC", "game": "英雄联盟"},
    {"name": "G2 Esports", "league": "LEC", "game": "英雄联盟"},
    {"name": "Movistar KOI", "league": "LEC", "game": "英雄联盟"},
    {"name": "Team Vitality", "league": "LEC", "game": "英雄联盟"},
    {"name": "GIANTX", "league": "LEC", "game": "英雄联盟"},
    {"name": "Team BDS", "league": "LEC", "game": "英雄联盟"},
    {"name": "Team Heretics", "league": "LEC", "game": "英雄联盟"},
    {"name": "SK Gaming", "league": "LEC", "game": "英雄联盟"},
    {"name": "Rogue", "league": "LEC", "game": "英雄联盟"}
]

# 战队图标对应表 - 可以根据需要添加更多图标URL
TEAM_ICONS = {
    "T1": "https://i.imgur.com/8HMvI1v.png",
    "Gen.G": "https://i.imgur.com/R6cPDM1.png",
    "DRX": "https://i.imgur.com/u3KoCVh.png",
    "Hanwha Life Esports": "https://i.imgur.com/XFX9Iil.png",
    "KT Rolster": "https://i.imgur.com/lHhfyU9.png",
    "Dplus KIA": "https://i.imgur.com/4LHvLvv.png",
    "Bilibili Gaming": "https://i.imgur.com/9d5lKKJ.png",
    "LNG Esports": "https://i.imgur.com/cQBOFIy.png",
    "EDward Gaming": "https://i.imgur.com/NnzgG4C.png",
    "Royal Never Give Up": "https://i.imgur.com/Q3VbQIh.png",
    "FunPlus Phoenix": "https://i.imgur.com/TlkVIlQ.png",
    "Weibo Gaming": "https://i.imgur.com/VT7hiDS.png",
    "Team WE": "https://i.imgur.com/0WaLVV9.png",
    "Oh My God": "https://i.imgur.com/lMVJOEG.png",
    "JD Gaming": "https://i.imgur.com/1QEA0h9.png",
    "Top Esports": "https://i.imgur.com/PbOj5W8.png",
    "G2 Esports": "https://i.imgur.com/xJqUEiW.png",
    "Fnatic": "https://i.imgur.com/YsOnD7I.png",
    "Team Vitality": "https://i.imgur.com/DHnZ8nZ.png",
    "SK Gaming": "https://i.imgur.com/nVwWVVR.png",
    "Team BDS": "https://i.imgur.com/eOjJHGA.png",
    "Rogue": "https://i.imgur.com/kqcm5QV.png"
}

def download_image(url, save_path):
    """
    下载图片并保存到指定路径
    """
    try:
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            with open(save_path, 'wb') as f:
                response.raw.decode_content = True
                shutil.copyfileobj(response.raw, f)
            return True
        else:
            print(f"下载失败 {url}: 状态码 {response.status_code}")
            return False
    except Exception as e:
        print(f"下载异常 {url}: {e}")
        return False

def clean_filename(name):
    """
    清理文件名，移除特殊字符
    """
    # 逐个替换特殊字符
    name = name.lower()
    name = name.replace(' ', '_')
    name = name.replace('.', '')
    name = name.replace('-', '_')
    name = name.replace("'", '')
    return f"{name}.png"

def update_teams():
    """
    更新战队信息到数据库
    """
    app = create_app()
    with app.app_context():
        # 创建图标目录
        icons_dir = os.path.join(app.static_folder, 'team_icons')
        os.makedirs(icons_dir, exist_ok=True)
        
        # 确保默认图标存在
        default_icon_path = os.path.join(icons_dir, 'default_team.png')
        if not os.path.exists(default_icon_path):
            # 创建一个简单的默认图标文件
            with open(default_icon_path, 'wb') as f:
                # 简单的灰色PNG图片数据
                f.write(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00d\x00\x00\x00d\x08\x02\x00\x00\x00\xff\x80\x02\x03\x00\x00\x00\x19IDATX\x85\xed\xc1\x01\x01\x00\x00\x00\x82 \xff\xafnH@\x01\x00\x00\x00\x00\x00\x00\x00\x00\xf0\r\x07\x0c\x00\x01\x9d\x1d\xd9\xec\x00\x00\x00\x00IEND\xaeB`\x82')
                print("创建了默认图标文件")
        
        # 获取当前数据库中的所有战队
        existing_teams = {team.name: team for team in Team.query.all()}
        
        # 获取新列表中的所有战队名称
        new_team_names = {team["name"] for team in TEAMS_DATA_2025}
        
        # 删除不在新列表中的战队
        for team_name, team in existing_teams.items():
            if team_name not in new_team_names:
                print(f"删除旧战队: {team_name}")
                db.session.delete(team)
        
        db.session.commit()
        
        teams_added = 0
        teams_updated = 0
        
        # 添加或更新战队
        for team_data in TEAMS_DATA_2025:
            team_name = team_data["name"]
            
            # 检查战队是否已存在
            existing_team = existing_teams.get(team_name)
            
            if existing_team:
                # 更新现有战队
                existing_team.league = team_data["league"]
                existing_team.game = team_data["game"]
                teams_updated += 1
                print(f"更新战队: {team_name}")
            else:
                # 下载或分配图标
                if team_name in TEAM_ICONS:
                    icon_url = TEAM_ICONS[team_name]
                    icon_filename = clean_filename(team_name)
                    icon_path = os.path.join(icons_dir, icon_filename)
                    
                    if download_image(icon_url, icon_path):
                        print(f"图标下载成功: {team_name}")
                    else:
                        print(f"图标下载失败: {team_name}, 使用默认图标")
                        icon_filename = 'default_team.png'
                else:
                    print(f"未找到图标URL: {team_name}, 使用默认图标")
                    icon_filename = 'default_team.png'
                
                # 创建新战队
                new_team = Team(
                    name=team_name,
                    league=team_data["league"],
                    game=team_data["game"],
                    icon=icon_filename,
                    total_matches=0,
                    wins=0
                )
                
                # 添加到数据库
                db.session.add(new_team)
                teams_added += 1
                print(f"添加新战队: {team_name}")
        
        # 提交事务
        db.session.commit()
        print(f"战队数据更新完成，新增 {teams_added} 支战队，更新 {teams_updated} 支战队")

if __name__ == "__main__":
    update_teams() 